export default class WebSocketService {
	private socket : WebSocket | null = null;
	private url : string;
	private onMessageCallback : ((message : any) => void) | null = null;
	private onErrorCallback : ((error : Event) => void) | null = null;
	private heartbeatInterval : ReturnType<typeof setInterval> | null = null;
	private reconnectInterval : number | null = null;
	private reconnectAttempts : number = 0;
	private isManualClose : boolean = false; // 标志位，用于判断是否是主动关闭

	constructor(url : string) {
		this.url = url;
	}

	public connect() {
		if (this.socket) {
			this.disconnect(); // 确保之前的连接已关闭
		}

		this.isManualClose = false; // 连接时重置标志位
		this.socket = new WebSocket(this.url);

		this.socket.onopen = () => {
			console.log('WebSocket connection established');
			this.startHeartBeat(); // 开始发送心跳
			this.reconnectAttempts = 0; // 重置重连尝试次数
		};

		this.socket.onmessage = (event) => {
			console.log('Message received:', event.data);
			if (this.onMessageCallback) {
				this.onMessageCallback(event.data);
			}
		};

		this.socket.onerror = (event) => {
			console.error('WebSocket error:', event);
			if (this.onErrorCallback) {
				this.onErrorCallback(event);
			}
		};

		this.socket.onclose = () => {
			console.log('WebSocket connection closed');
			this.stopHeartBeat(); // 停止发送心跳

			// 检查是否是主动关闭，如果不是则尝试重连
			if (!this.isManualClose) {
				this.reconnect();
			}
		};
	}

	public send(message : string) {
		if (this.socket && this.socket.readyState === WebSocket.OPEN) {
			this.socket.send(message);
			console.log('Message sent:', message);
		} else {
			console.error('WebSocket is not open. Unable to send message.');
		}
	}

	private sendHeartBeat() {
		if (this.socket && this.socket.readyState === WebSocket.OPEN) {
			this.socket.send('heartbeat');
			console.log('Heartbeat sent');
		} else {
			console.error('WebSocket is not open. Unable to send heartbeat.');
		}
	}

	private startHeartBeat() {
		this.stopHeartBeat(); // 确保不会有多个定时器运行
		this.heartbeatInterval = setInterval(() => this.sendHeartBeat(), 10000); // 每隔10秒发送心跳
	}

	private stopHeartBeat() {
		if (this.heartbeatInterval) {
			clearInterval(this.heartbeatInterval);
			this.heartbeatInterval = null;
		}
	}

	public disconnect() {
		console.log("WebSocketService disconnect")
		this.isManualClose = true; // 设置标志位为主动关闭
		if (this.socket) {
			this.socket.close(); // 关闭 WebSocket 连接
			this.socket = null;
		}
		this.stopHeartBeat(); // 停止发送心跳
		if (this.reconnectInterval) {
			clearTimeout(this.reconnectInterval);
			this.reconnectInterval = null;
		}
	}

	private reconnect() {
		if (this.reconnectAttempts < 5) {
			this.reconnectAttempts++;
			console.log(`Reconnecting... Attempt ${this.reconnectAttempts}`);
			this.reconnectInterval = window.setTimeout(() => this.connect(), 2000); // 2秒后尝试重连
		} else {
			console.warn('Max reconnect attempts reached');
		}
	}

	public close() {
		this.disconnect();
		console.log('WebSocket connection closed manually');
	}

	public setOnMessageCallback(callback : (message : any) => void) {
		this.onMessageCallback = callback;
	}

	public setOnErrorCallback(callback : (error : Event) => void) {
		this.onErrorCallback = callback;
	}
}